import { Injectable } from '@nestjs/common';
import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint } from 'class-validator';
import { ValidatorConstraintInterface } from 'class-validator/types/validation/ValidatorConstraintInterface';
import { Connection } from 'typeorm';
import { InjectConnection } from '@nestjs/typeorm';

@ValidatorConstraint({ async: true })
@Injectable()
export class EntityExistsConstraint implements ValidatorConstraintInterface {

  constructor(@InjectConnection() private dbConnection: Connection) {
  }

  defaultMessage(validationArguments?: ValidationArguments): string {
    return `${validationArguments.constraints[0].name} with ${validationArguments.property} already exists`;
  }

  validate(value: any, validationArguments?: ValidationArguments): Promise<boolean> | boolean {
    const repoName = validationArguments.constraints[0];
    const property = validationArguments.property;
    const repository = this.dbConnection.getRepository(repoName);
    return repository.findOne({ [property]: value }).then(result => {
      return !result;
    });
  }

}

export function EntityExists(repoName, validationOptions?: ValidationOptions) {
  return function(object: any, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [repoName],
      validator: EntityExistsConstraint,
    });
  };
}